package com.dmagic.cms.controller;

import java.math.BigInteger;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.dmagic.cms.common.annotation.FormModel;
import com.dmagic.cms.common.annotation.RequestJsonParam;
import com.dmagic.cms.common.controller.CommonController;
import com.dmagic.cms.common.query.ConditionsBean;
import com.dmagic.cms.common.query.PageUtil;
import com.dmagic.cms.common.util.JsonUtil;
import com.dmagic.cms.common.util.NumberUtil;
import com.dmagic.cms.common.util.StringUtil;
import com.dmagic.cms.entity.Language;
import com.dmagic.cms.entity.Language.Lang;
import com.dmagic.cms.entity.Product;
import com.dmagic.cms.entity.ProductCategory;
import com.dmagic.cms.entity.UploadFileInfo;
import com.dmagic.cms.service.BaseService;
import com.dmagic.cms.service.ProductCategoryService;
import com.dmagic.cms.service.ProductService;

@Controller
@RequestMapping(value = "/product")
public class ProductController extends CommonController {

	private String PRODUCT_LIST = "product/productList";

	private String PRODUCT_ADD = "product/productAdd";

	static {

	}

	@Autowired
	private BaseService baseService;

	@Autowired
	private ProductService productService;

	@Autowired
	private ProductCategoryService productCategoryService;

	@RequestMapping()
	public String list(Model model) {
		List<Language> languages = baseService.getAllLanguages();
		model.addAttribute("language", languages);
		for (Language language : languages) {
			List<ProductCategory> categorys = productCategoryService.getAllProductCategoryByLanguage(language
					.getLanguageId());
			model.addAttribute(language.getLanguageKey() + "Category", categorys);
		}
		return PRODUCT_LIST;
	}

	@RequestMapping(value = "search", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public String search(@RequestParam Integer pageNo, @RequestParam Integer pageSize,
			@RequestParam String orderType, @RequestParam String orderBy,
			@RequestJsonParam("rules") List<ConditionsBean> conditions) throws Exception {
		PageUtil<Map> pageUtil = new PageUtil<Map>();
		pageUtil.setAutoCount(true);
		pageUtil.setPageNo(pageNo);
		pageUtil.setPageSize(pageSize);
		pageUtil.setOrder(orderType);
		pageUtil.setOrderBy(orderBy);
		pageUtil.setConditions(conditions);
		productService.searchProduct(pageUtil);
		return JsonUtil.toFullJsonWithDateFormat(pageUtil, DATE_FORMAT);

	}

	@RequestMapping("edit/{productNo}")
	public String edit(@PathVariable("productNo") String productNo,
			@RequestParam("languageId") Long languageId, Model model) {
		List<Product> product = productService.getProductByProductNo(productNo);
		List<Language> languages = baseService.getAllLanguages();
		lang: for (Language l : languages) {
			String languageKey = l.getLanguageKey();
			if (NumberUtil.equals(languageId, l.getLanguageId())) {
				model.addAttribute("defaultForm", languageKey);
			}
			for (Product n : product) {
				if (l.getLanguageId() == n.getLanguageId()) {
					model.addAttribute(languageKey, n);
					List<UploadFileInfo> uploadFileInfo = baseService
							.getUploadFileInfoListByUploadFileSetInfoId(n.getUploadFileSetInfoId());
					model.addAttribute(languageKey + "_uploadFileInfo", uploadFileInfo);
					continue lang;
				}
			}
		}
		model.addAttribute("language", languages);
		for (Language language : languages) {
			List<ProductCategory> categorys = productCategoryService.getAllProductCategoryByLanguage(language
					.getLanguageId());
			model.addAttribute(language.getLanguageKey() + "Category", categorys);
		}
		return PRODUCT_ADD;
	}

	@ModelAttribute("preProduct")
	public Product getProduct(Long productId) {
		if (productId == null) {
			return new Product();
		}
		return productService.getProduct(productId);
	}

	@RequestMapping("add")
	public String add(Model model) {
		Product product = new Product();
		product.setProductNo(getDateFormatNo());
		model.addAttribute("defaultForm", Lang.zh_HK.getValue());
		model.addAttribute(Lang.zh_HK.getValue(), product);
		model.addAttribute(Lang.en.getValue(), product);
		List<Language> languages = baseService.getAllLanguages();
		model.addAttribute("language", languages);
		for (Language language : languages) {
			List<ProductCategory> categorys = productCategoryService.getAllProductCategoryByLanguage(language
					.getLanguageId());
			model.addAttribute(language.getLanguageKey() + "Category", categorys);
		}
		return PRODUCT_ADD;
	}

	@RequestMapping("save")
	public String save(@FormModel("zh") Product zhProduct, @FormModel("en") Product enProduct,
			RedirectAttributes redirectAttributes) {
		productService.saveProduct(new Product[] { zhProduct, enProduct });
		redirectAttributes.addFlashAttribute(SUCCESS, "Save Successful.");
		return "redirect:/product.do";
	}

	@RequestMapping("delete")
	@ResponseBody
	public String delete(@RequestJsonParam("productIds") List<Long> productIds) {
		productService.deleteProduct(productIds);
		return "Delete Successful.";
	}

	@RequestMapping("delete/{productId}")
	@ResponseBody
	public String delete(@PathVariable("productId") Long productId) {
		productService.deleteProduct(productId);
		return "Delete Successful.";
	}

	@RequestMapping("top/{productId}")
	@ResponseBody
	public String top(@PathVariable("productId") Long productId, @RequestParam("isTop") Boolean isTop) {
		Product product = getProduct(productId);
		product.setIsTop(!isTop);
		productService.saveProduct(new Product[] { product });
		return "Successful.";
	}

	@RequestMapping("publish/{productId}")
	@ResponseBody
	public String publish(@PathVariable("productId") Long productId,
			@RequestParam("productStatus") Boolean productStatus) {
		Product product = getProduct(productId);
		product.setProductStatus(!productStatus);
		productService.saveProduct(new Product[] { product });
		return "Successful.";
	}

	@InitBinder
	public void initBinder(WebDataBinder b) {
		DateFormat fmt = new SimpleDateFormat(DATE_FORMAT);
		CustomDateEditor dateEditor = new CustomDateEditor(fmt, true);
		b.registerCustomEditor(Date.class, "productDate", dateEditor);
	}

	@RequestMapping(value = "query", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public String query(@RequestParam Integer pageNo, @RequestParam Integer pageSize,
			@RequestParam String orderType, @RequestParam String orderBy,
			@RequestJsonParam("rules") List<ConditionsBean> conditions) throws Exception {
		PageUtil<Map> pageUtil = new PageUtil<Map>();
		pageUtil.setAutoCount(true);
		pageUtil.setPageNo(pageNo);
		pageUtil.setPageSize(pageSize);
		pageUtil.setOrder(orderType);
		pageUtil.setOrderBy(orderBy);
		pageUtil.setConditions(conditions);
		productService.searchProduct(pageUtil);
		List<Map> list = pageUtil.getResult();
		for (Map m : list) {
			java.math.BigInteger fileId = (BigInteger) m.get("uploadFileSetInfoId");
			if (fileId != null) {
				List<UploadFileInfo> uploadFileInfo = baseService
						.getUploadFileInfoListByUploadFileSetInfoId(fileId.longValue());
				m.put("files", uploadFileInfo);
			}
		}
		return JsonUtil.toFullJsonWithDateFormat(pageUtil, DATE_FORMAT);
	}

	@RequestMapping(value = "changeCategory", produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String changeCategory(@RequestJsonParam("productIds") List<Long> productIds, Long categoryId) {
		if (null == categoryId) {
			return "產品類別為空！";
		}
		productService.changeProductCategory(productIds, categoryId);
		return "Successful.";
	}

	@RequestMapping(value = "web/productDetail/{productId}", produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String getProductDetailByProductId(@PathVariable("productId") Long productId) {
		if (productId == null) {
			return "NO-DATAS";
		}
		return productService.getProduct(productId).getProductContent();
	}

	@RequestMapping("web/heatMap/{productId}")
	public String getProductInfo(@PathVariable("productId") Long productId, @RequestParam Long languageId,
			Model model) {
		Product product = productService.getProduct(productId);
		List<UploadFileInfo> uploadFileInfo = baseService.getUploadFileInfoListByUploadFileSetInfoId(product
				.getUploadFileSetInfoId());
		model.addAttribute("product", product);
		model.addAttribute("files", uploadFileInfo);
		model.addAttribute("language", languageId);
		return "web/product/productHeat";
	}

}
